package com.ruicar.afs.cloud.apply.pre.approve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.apply.business.service.ApplySequenceService;
import com.ruicar.afs.cloud.apply.common.dto.ApplyWechatDTO;
import com.ruicar.afs.cloud.apply.common.entity.ApplyCustBaseInfo;
import com.ruicar.afs.cloud.apply.common.entity.PreApproveInfo;
import com.ruicar.afs.cloud.apply.common.feign.Apply2ChannelFeign;
import com.ruicar.afs.cloud.apply.common.feign.ApplyWechatFegin;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.condition.ChannelCondition;
import com.ruicar.afs.cloud.apply.contract.enums.CertTypePictureEnum;
import com.ruicar.afs.cloud.apply.contract.enums.UploadIDImageSceneEnum;
import com.ruicar.afs.cloud.apply.contract.vo.ContractFileVo;
import com.ruicar.afs.cloud.apply.pre.approve.condition.PreApproveCondition;
import com.ruicar.afs.cloud.apply.pre.approve.mapper.PreApproveMapper;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.approve.utils.ImageUploadUtil;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyReportCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyCustBaseInfoMapper;
import com.ruicar.afs.cloud.apply.pre.loan.mapper.ApplyOrderInfoMapper;
import com.ruicar.afs.cloud.apply.pre.smallprogram.condition.TencentCloudNuclearBodyCondition;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.enums.StatusEnum;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.mapper.ComAttachmentManagementMapper;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.ComAttachmentManagementService;
import com.ruicar.afs.cloud.parameter.commom.enums.CustType;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.ruicar.afs.cloud.apply.common.utils.ApplyConstants.MESSAGE_TYPE_ZERO;

/**
 * @Description:预审批service实现类
 * @Author:jihuigeng
 * @Date:2020/5/9 19:01
 * @Version: V1.0
 **/
@Service
@AllArgsConstructor
@Slf4j
public class PreApproveServiceImpl extends ServiceImpl<PreApproveMapper, PreApproveInfo> implements PreApproveService {

    private final ImageUploadUtil getTempDir;
    private final ComAttachmentManagementMapper managementMapper;
    private final PreApproveMapper preApproveMapper;
    private final ApplyOrderInfoMapper applyOrderInfoMapper;
    private final ApplyCustBaseInfoMapper custBaseInfoMapper;
    private final StringRedisTemplate stringRedisTemplate;
    private final ApplyWechatFegin applyWechatFegin;
    private final Apply2ChannelFeign apply2ChannelFeign;
    private final ApplyConfig config;
    private final ComAttachmentFileService comAttachmentFileService;
    private final ComAttachmentManagementService attachmentManagementService;
    private final ApplySequenceService applySequenceService;

    @Override
    public Map savePreInfo(PreApproveCondition condition) {
        Map<String, String> requestHeader = new HashMap<>();
        requestHeader.put("clientId", config.getChannelClientId());
        requestHeader.put("clientSecret", config.getChannelClientSecret());
        //验证证件有效期
        if (StringUtil.isEmpty(condition.getIsLongTerm())) {
            if (condition.getCertEndDate() == null) {
                throw new AfsBaseException("证件结束日期不能为空");
            } else if (condition.getCertEndDate().compareTo(new Date()) < 0) {
                throw new AfsBaseException("证件已过有效期");
            }
        }
        //根据身份证号，业务类型,部门id查询信息
        PreApproveCondition preApproveCondition = new PreApproveCondition();
        preApproveCondition.setCertNo(condition.getCertNo());
        preApproveCondition.setBusinessType(condition.getBusinessType());
        preApproveCondition.setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray(ApplyConstants.DEPT_IDS);
        if (jsonArray != null) {
            preApproveCondition.setDeptIds(jsonArray.toJavaList(String.class));
        }
        List<PreApproveInfo> preApproveInfoList = this.preApproveMapper.getPreApproveInfo(preApproveCondition);
        //客户做过预审批
        if (CollectionUtil.isNotEmpty(preApproveInfoList)) {
            for (PreApproveInfo preApproveInfo : preApproveInfoList) {
                //新车业务
                if (ApplyConstants.BUSINESS_TYPE_NEW_CAR.equals(preApproveInfo.getBusinessType())) {
                    if (ApplyConstants.PRE_APPROVE_INVALID.equals(preApproveInfo.getApplyStatus())) {
                        //保存并生成二维码
                        this.savePreInfo(preApproveInfo);
                        //上传证件照
                        this.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode(), null, String.valueOf(preApproveInfo.getId()));
                        Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                        return qrCode;
                    } else if (ApplyConstants.PRE_APPROVE_PASS.equals(preApproveInfo.getApplyStatus())) {
                        //查询到相同订单，已通过,且在有效期内
                        //todo 预审批结果有效期
                        //判断是否是同一家SP,是，不生成二维码，提示已通过，不是，可以保存，生成二维码
                        ChannelCondition channelCondition = new ChannelCondition();
                        channelCondition.setChannelId(preApproveInfo.getChannelId().toString());
                        IResponse channelBaseInfo = this.apply2ChannelFeign.getChannelBaseInfo(channelCondition, requestHeader);
                        //同一家SP,已经通过的不可以再做
                        if (ObjectUtil.isNotNull(channelBaseInfo.getData())) {
                            throw new AfsBaseException("同一家SP下,该订单已经做过该业务");
                        } else if (ObjectUtil.isNull(channelBaseInfo.getData())) {
                            //保存并生成二维码
                            this.savePreInfo(preApproveInfo);
                            Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                            return qrCode;
                        }
                    } else if (preApproveInfo.getApplyDate() == null) {
                        //暂存的单子,
                        preApproveInfo.setApplyDate(new Date());
                        preApproveInfo.setSellerPhone(condition.getSellerPhone());
                        //保存并生成二维码
                        this.updateById(preApproveInfo);
                        Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                        return qrCode;
                    } else {
                        throw new AfsBaseException("您已做过该业务");
                    }
                } else if (ApplyConstants.BUSINESS_TYPE_OLD_CAR.equals(condition.getBusinessType())) {
                    //二手车业务
                    //拒绝的单子，可以重新新增做预审批
                    if (ApplyConstants.PRE_APPROVE_REFUSE.equals(preApproveInfo.getApplyStatus())) {
                        //保存并生成二维码
                        this.savePreInfo(preApproveInfo);
                        Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                        return qrCode;
                    } else if (ApplyConstants.PRE_APPROVE_PASS.equals(preApproveInfo.getApplyStatus())) {
                        //判断是否在有效期
                        //判断是否是同一家SP,是，不生成二维码，提示已通过，不是，可以保存，生成二维码
                        ChannelCondition channelCondition = new ChannelCondition();
                        channelCondition.setChannelId(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").get("channelBelong").toString());
                        IResponse channelBaseInfo = this.apply2ChannelFeign.getChannelBaseInfo(channelCondition, requestHeader);
                        //同一家SP,已经通过的不可以再做
                        if (ObjectUtil.isNotNull(channelBaseInfo.getData())) {
                            throw new AfsBaseException("同一家SP下,该订单已经通过");
                        } else if (ObjectUtil.isNull(channelBaseInfo.getData())) {
                            //保存预审批信息
                            this.savePreInfo(preApproveInfo);
                            Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                            return qrCode;
                        }
                    } else if (preApproveInfo.getApplyDate() == null) {
                        //暂存的单子,
                        preApproveInfo.setApplyDate(new Date());
                        String applyNo = applySequenceService.getApplyNo(preApproveInfo.getBusinessType());
                        log.info("预审批临时编号变更正是编号:{}", applyNo);
                        preApproveInfo.setApplyNo(applyNo);
                        //保存并生成二维码
                        this.updateById(preApproveInfo);
                        preApproveInfo.setSellerPhone(condition.getSellerPhone());
                        preApproveInfo.setSellerRealName(condition.getSellerRealName());
                        Map qrCode = this.getQrCode(preApproveInfo.getId(), null, null);
                        return qrCode;
                    } else {
                        throw new AfsBaseException("您已做过该业务");
                    }
                }
            }
        } else if (CollectionUtil.isEmpty(preApproveInfoList)) {
            //客户没做过预审批
            //新增状态默认为待提交
            condition.setApplyStatus(ApplyConstants.PRE_APPROVE_PRE_SUBMIT);
            //新增时的创建人
            condition.setCreateBy(SecurityUtils.getUsername());
            //新增时的申请时间
            condition.setApplyDate(new Date());
            //部门id
            condition.setDeptId(SecurityUtils.getUser().getDeptId().toString());
            //新增时的创建时间
            condition.setCreateTime(new Date());
            condition.setSellerRealName(SecurityUtils.getUser().getUserRealName());
            //渠道id
            condition.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
            condition.setChannelName(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").get("channelFullName").toString());
            //新增预审批
            String applyNo = applySequenceService.getApplyNo(condition.getBusinessType());
            log.info("预审批临时编号变更正是编号:{}", applyNo);
            condition.setApplyNo(applyNo);
            this.save(condition);
            PreApproveInfo approveInfo = this.getOne(Wrappers.<PreApproveInfo>query().lambda()
                    .eq(StringUtil.isNotEmpty(condition.getCertNo()), PreApproveInfo::getCertNo, condition.getCertNo())
                    .eq(StringUtil.isNotEmpty(condition.getBusinessType()), PreApproveInfo::getBusinessType, condition.getBusinessType())
                    .eq(StringUtil.isNotEmpty(SecurityUtils.getUsername()), PreApproveInfo::getCreateBy, SecurityUtils.getUsername()));
            //新增，生成二维码
            Map qrCode = this.getQrCode(approveInfo.getId(), null, null);
            //上传证件照
            return qrCode;
        }
        return null;
    }

    /**
     * 预审批编辑
     *
     * @param condition
     */
    @Override
    public Map editPreInfo(PreApproveCondition condition) {
        //是否长期不为空，且证件有效期不为空
        if (StringUtil.isEmpty(condition.getIsLongTerm())) {
            if (condition.getCertEndDate() == null) {
                throw new AfsBaseException("证件结束日期不能为空");
            } else if (DateUtil.format(condition.getCertEndDate(), "yyyy-MM-dd").compareTo(DateUtil.format(new Date(), "yyyy-MM-dd")) < 0) {
                //验证证件有效期
                throw new AfsBaseException("证件已过有效期");
            }
        }
        //使用姓名,证件号,业务类型，查询同一SP下的预审批信息
        PreApproveCondition preApproveCondition = new PreApproveCondition();
        preApproveCondition.setCertNo(condition.getCertNo());
        preApproveCondition.setBusinessType(condition.getBusinessType());
        preApproveCondition.setCreateBy(SecurityUtils.getUsername());
        JSONArray jsonArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray(ApplyConstants.DEPT_IDS);
        if (jsonArray != null) {
            preApproveCondition.setDeptIds(jsonArray.toJavaList(String.class));
        }
        List<PreApproveInfo> preApproveInfoList = this.preApproveMapper.getPreApproveInfo(preApproveCondition);
        //根据证件号，业务类型，查询出预审批信息
        //如果查询为空,那么就是一个新的单子
        if (CollectionUtil.isEmpty(preApproveInfoList)) {
            condition.setUpdateBy(SecurityUtils.getUsername());
            condition.setCreateTime(new Date());
            this.updateById(condition);
            //预审批影像件上传及更新
            this.uplodPreCard(condition);
            //待提交的可以编辑，并生成二维码
            Map qrCode = this.getQrCode(condition.getId(), null, null);
            return qrCode;
        } else {
            for (PreApproveInfo preApproveInfo : preApproveInfoList) {
                String applyStatus = preApproveInfo.getApplyStatus();
                //待提交订单,点击保存，生成二维码，进行小程序验证
                if (ApplyConstants.PRE_APPROVE_PRE_SUBMIT.equals(applyStatus)) {
                    this.editPreInfo(preApproveInfo, condition);
                    this.uplodPreCard(condition);
                    Map qrCode = this.getQrCode(condition.getId(), null, null);
                    return qrCode;
                } else if (ApplyConstants.PRE_APPROVE_BACK.equals(applyStatus)) {
                    //退回,点击保存，订单重新激活，生成二维码，进行小程序验证
                    this.editPreInfo(preApproveInfo, condition);
                    this.uplodPreCard(condition);
                    Map qrCode = this.getQrCode(condition.getId(), null, null);
                    return qrCode;
                }
            }
        }
        return null;
    }


    /**
     * 编辑更新预审批信息
     *
     * @param preApproveInfo
     * @param condition
     */
    public void editPreInfo(PreApproveInfo preApproveInfo, PreApproveCondition condition) {
        preApproveInfo.setCustName(condition.getCustName());
        preApproveInfo.setTelPhone(condition.getTelPhone());
        preApproveInfo.setCertNo(condition.getCertNo());
        preApproveInfo.setIsLongTerm(condition.getIsLongTerm());
        preApproveInfo.setCertEndDate(condition.getCertEndDate());
        preApproveInfo.setUpdateTime(new Date());
        preApproveInfo.setUpdateBy(SecurityUtils.getUsername());
        this.updateById(preApproveInfo);
    }

    /**
     * 预审批影像件上传及更新
     *
     * @param condition
     */
    public void uplodPreCard(PreApproveCondition condition) {
        //上传证件照
        if (condition.getPcOrApp().equals(ApplyConstants.PC_UPLOAD)) {
            if (condition.getContractFileVos() != null) {
                this.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex());
                this.queryAndRemove(condition.getId().toString(), CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex());
                this.saveOrUpdateFile(condition.getContractFileVos(), condition.getId().toString());
            }
        } else if (condition.getPcOrApp().equals(ApplyConstants.APP_UPLOAD)) {
            this.storeCardImage(condition.getFrontIDCard(), condition.getReverseIDCard(), UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode(), null, String.valueOf(condition.getId()));
        }
    }

    /**
     * 删除预审批影像资料
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public String queryAndRemove(String id, String type) {
        ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, type));
        //先查询
        List<ComAttachmentFile> attachmentFile = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, id).eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagement.getId().toString()));
        if (attachmentFile.size() > 0) {
            for (ComAttachmentFile comAttachmentFile1 : attachmentFile) {
                this.comAttachmentFileService.removeById(comAttachmentFile1);
                log.info("{}", comAttachmentFile1.getId() + "删除成功");
            }
        }
        return null;
    }

    /**
     * 二维码信息封装
     *
     * @param id
     * @return
     */
    @Override
    public Map getQrCode(Long id, String applyNo, String flag) {
        TencentCloudNuclearBodyCondition bodyCondition = new TencentCloudNuclearBodyCondition();
        if (ApplyConstants.PRINCIPAL_BORROWER.equals(flag)) {
            bodyCondition.setSignScene(ApplyConstants.PRINCIPAL_BORROWER);
            bodyCondition.setCustId(id);
            bodyCondition.setApplyNo(applyNo);
        } else if (ApplyConstants.COMMON_BORROWER.equals(flag)) {
            bodyCondition.setSignScene(ApplyConstants.COMMON_BORROWER);
            bodyCondition.setCustId(id);
            bodyCondition.setApplyNo(applyNo);
        } else if (ApplyConstants.GUARANTOR.equals(flag)) {
            bodyCondition.setSignScene(ApplyConstants.GUARANTOR);
            bodyCondition.setCustId(id);
            bodyCondition.setApplyNo(applyNo);
        } else {
            bodyCondition.setSignScene(ApplyConstants.MESSAGE_TYPE_ZERO);
            bodyCondition.setPreId(id);
        }
        Map qrCode = this.getSmallProgramQrCode(bodyCondition);
        qrCode.put("id", id);
        return qrCode;
    }


    /**
     * 根据ID查询预审批信息
     *
     * @param id
     * @return
     */
    @Override

    public PreApproveInfo getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * 公用的附件上传方法:
     *
     * @param frontIDCard   正面照base64-（正反二选一/都传）
     * @param reverseIDCard 反面照base64-（正反二选一/都传）
     * @param custRole      客户角色-（可选）
     * @param params        id/申请编号-（必传）
     * @param uploadScene   场景-必传
     */
    public void uploadFileMethod(String frontIDCard, String reverseIDCard, String uploadScene, String custRole, String params) {
        this.storeCardImage(frontIDCard, reverseIDCard, custRole, uploadScene, params);
    }

    /**
     * 保存身份证正反面至服务
     *
     * @param frontIDCard
     * @param reverseIDCard
     */
    @Override
    public void storeCardImage(String frontIDCard, String reverseIDCard, String uploadScene, String custRole, String params) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Authorization", this.getTempDir.getAuthorization());
        String s = null;
        String fileName = null;
        Map<String, String> map = null;
        //正面
        if (StringUtil.isNotEmpty(frontIDCard)) {
            //客户信息start
            if (UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getName();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getName();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getName();
                }
                //客户信息正面证件照
                map = getTempDir.doUpload(frontIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("客户身份证正面保存成功:{}", params);
            }
            //预审批start
            if (UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex();
                fileName = CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getName();
                //预审批正面证件照
                map = getTempDir.doUpload(frontIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("预审批身份证正面保存成功:{}", params);
            }
            //合同录入-客户证件上传start
            if (UploadIDImageSceneEnum.CONTRACTCUST.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getName();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getName();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getIndex();
                    fileName = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getName();
                }
                //客户信息正面证件照
                map = getTempDir.doUpload(frontIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息正面证件照保存成功:{}", params);
            }
            //合同录入-发票上传start
            if (UploadIDImageSceneEnum.INVOICE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_FRONT.getIndex();
                fileName = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_FRONT.getName();
                //预审批正面证件照
                map = getTempDir.doUpload(frontIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("合同发票图片保存成功:{}", params);
            }
        }
        //反面
        if (StringUtil.isNotEmpty(reverseIDCard)) {
            //客户信息start
            if (UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getName();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getName();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getName();
                }
                //客户信息反面证件照
                map = getTempDir.doUpload(reverseIDCard, fileName, headers);
                //保存到file表
                this.setImageStore(s, map, params);
                log.info("客户身份证反面保存成功:{}", params);
            }
            //预审批start
            if (UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex();
                fileName = CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getName();
                //预审批反面证件照
                map = getTempDir.doUpload(reverseIDCard, fileName, headers);
                //保存到file表
                this.setImageStore(s, map, params);
                log.info("预审批身份证反面保存成功:{}", params);
            } //合同录入-客户证件上传start
            if (UploadIDImageSceneEnum.CONTRACTCUST.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getName();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getName();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getIndex();
                    fileName = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getName();
                }
                //客户信息反面证件照
                map = getTempDir.doUpload(reverseIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息反面证件照保存成功:{}", params);
            }
            //合同录入-发票上传start
            if (UploadIDImageSceneEnum.INVOICE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_BACK.getIndex();
                fileName = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_BACK.getName();
                //预审批正面证件照
                map = getTempDir.doUpload(reverseIDCard, fileName, headers);
                this.setImageStore(s, map, params);
                log.info("合同发票图片保存成功:{}", params);
            }
        }
    }

    @Override
    public void storeCardFileImage(MultipartFile frontIDCardFile, MultipartFile reverseIDCardFile, String uploadScene, String custRole, String params) {
        Map<String, String> headers = new HashMap<>(3);
        headers.put("Authorization", this.getTempDir.getAuthorization());
        String s = null;
        Map<String, String> map = null;
        //正面
        if (StringUtil.isNotEmpty(String.valueOf(frontIDCardFile))) {
            //客户信息start
            if (UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getIndex();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getIndex();
                }
                //客户信息正面证件照
                map = getTempDir.doUpload(frontIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息正面证件照保存成功:{}", params);
            }
            //预审批start
            if (UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getIndex();
                //预审批正面证件照
                map = getTempDir.doUpload(frontIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("预审批身份证正面保存成功:{}", params);
            }
            //合同录入-客户证件上传start
            if (UploadIDImageSceneEnum.CONTRACTCUST.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getIndex();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getIndex();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getIndex();
                }
                //客户信息正面证件照
                map = getTempDir.doUpload(frontIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息正面证件照保存成功:{}", params);
            }
            //合同录入-发票上传start
            if (UploadIDImageSceneEnum.INVOICE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_FRONT.getIndex();
                map = getTempDir.doUpload(frontIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("合同发票图片保存成功:{}", params);
            }
        }
        //反面
        if (StringUtil.isNotEmpty(String.valueOf(reverseIDCardFile))) {
            //客户信息start
            if (UploadIDImageSceneEnum.CUSTOMER_INFO_ID_CARD_IMAGE_SCENE.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getIndex();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getIndex();
                }
                //客户信息反面证件照
                map = getTempDir.doUpload(reverseIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息反面证件照保存成功:{}", params);
            }
            //预审批start
            if (UploadIDImageSceneEnum.PRE_APPROVE_SCENE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getIndex();
                //预审批反面证件照
                map = getTempDir.doUpload(reverseIDCardFile, headers);
                //保存到file表
                this.setImageStore(s, map, params);
                log.info("预审批身份证正面保存成功:{}", params);
            } //合同录入-客户证件上传start
            if (UploadIDImageSceneEnum.CONTRACTCUST.getCode().equals(uploadScene)) {
                if (ApplyConstants.PRINCIPAL_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getIndex();
                } else if (ApplyConstants.COMMON_BORROWER.equals(custRole)) {
                    s = CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getIndex();
                } else if (ApplyConstants.GUARANTOR.equals(custRole)) {
                    s = CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getIndex();
                }
                //客户信息反面证件照
                map = getTempDir.doUpload(reverseIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("客户信息反面证件照保存成功:{}", params);
            }
            //合同录入-发票上传start
            if (UploadIDImageSceneEnum.INVOICE.getCode().equals(uploadScene)) {
                s = CertTypePictureEnum.CONTRACT_INVOICE_ID_CARD_BACK.getIndex();
                map = getTempDir.doUpload(frontIDCardFile, headers);
                this.setImageStore(s, map, params);
                log.info("合同发票图片保存成功:{}", params);
            }
        }
    }

    /**
     * 保存MD5到file
     *
     * @param s
     */
    @Override
    public void setImageStore(String s, Map<String, String> map, String params) {
        //查询manage文件表内的数据
        ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
        ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, s));
        //先查询
        ComAttachmentFile attachmentFile = this.comAttachmentFileService.getOne(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, params).eq(StringUtil.isNotEmpty(comAttachmentManagement.getAttachmentName()), ComAttachmentFile::getAttachmentName, comAttachmentManagement.getAttachmentName()));
        if (ObjectUtil.isNotNull(attachmentFile)) {
            attachmentFile.setFileId(map.get("md5"));
            this.comAttachmentFileService.updateById(attachmentFile);
            log.info("{}", attachmentFile.getAttachmentName() + "更新成功");
        } else {
            if (ObjectUtil.isNotNull(comAttachmentManagement)) {
                comAttachmentFile.setBelongNo(params);
                comAttachmentFile.setBusiNo(params);
                comAttachmentFile.setAttachmentCode(String.valueOf(comAttachmentManagement.getId()));
                comAttachmentFile.setAttachmentName(comAttachmentManagement.getAttachmentName());
                comAttachmentFile.setFileStatus("standard");
                comAttachmentFile.setFileType("jpg");
                comAttachmentFile.setFileId(map.get("md5"));
                comAttachmentFile.setHistoryVersion(ApplyConstants.ZERO);
                comAttachmentFile.setIsElectronic(ApplyConstants.ZERO);
                comAttachmentFile.setFileName(comAttachmentManagement.getAttachmentName() + ".jpg");
                comAttachmentFile.setUploadTime(new Date());
                comAttachmentFile.setCreateBy(SecurityUtils.getUsername());
            }
            //存到file表
            this.comAttachmentFileService.save(comAttachmentFile);
            log.info("{}", comAttachmentManagement.getAttachmentName() + "更新成功");
        }
    }

    /**
     * 获取身份证，正反面文件:file_id,type
     * id/applyNo二选一
     *
     * @param id
     * @param applyNo
     * @return
     */
    @Override
    public Map<String, String> getFileId(String id, String applyNo) {
        Map<String, String> map = new HashMap<>(6);
        String param = null;
        if (StringUtil.isNotEmpty(id)) {
            param = id;
        } else if (StringUtil.isNotEmpty(applyNo)) {
            param = applyNo;
        }
        List<ComAttachmentFile> list = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query()
                .lambda().eq(ComAttachmentFile::getBusiNo, param));
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(comAttachmentFile -> {
                //正面
                if (CertTypePictureEnum.PRE_BORROWER_ID_CARD_FRONT.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("preBorrowerIdCardFront", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("preBorrowerFrontFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //反面
                if (CertTypePictureEnum.PRE_BORROWER_ID_CARD_BACK.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("preBorrowerIdCardBack", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("preBorrowerBackFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //主借人正面
                if (CertTypePictureEnum.MAIN_BORROWER_ID_CARD_FRONT.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("mainBorrowerIdCardFront", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("mainBorrowerFrontFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //主借人反面
                if (CertTypePictureEnum.MAIN_BORROWER_ID_CARD_BACK.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("mainBorrowerIdCardBack", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("mainBorrowerBackFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //共借人正面
                if (CertTypePictureEnum.COM_BORROWER_ID_CARD_FRONT.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("comBorrowerIdCardFront", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("comBorrowerFrontFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //共借人反面
                if (CertTypePictureEnum.COM_BORROWER_ID_CARD_BACK.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("comBorrowerIdCardBack", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("comBorrowerBackFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //担保人正面
                if (CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_FRONT.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("guarantorBorrowerIdCardFront", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("guarantorBorrowerFrontFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
                //担保人反面
                if (CertTypePictureEnum.GUARANTOR_BORROWER_ID_CARD_BACK.getName().equals(comAttachmentFile.getAttachmentName())) {
                    map.put("guarantorBorrowerIdCardBack", String.valueOf(comAttachmentFile.getFileId()));
                    map.put("guarantorBorrowerBackFileType", String.valueOf(comAttachmentFile.getFileType()));
                }
            });
        }
        return map;
    }


    /**
     * 获取微信二维码token
     *
     * @return
     */
    @Override
    public Map getToken() {
        Map<String, String> map = new HashMap(4);
        Map<String, String> header = new HashMap<>(4);
        header.put("grant_type", "client_credential");
        header.put("appid", "wxdccf9f85a15b3173");
        header.put("secret", "42274ebf1a5a339f10d7c1da1092dc1a");
        JSONObject token = this.applyWechatFegin.getToken(header);
        map.put("access_token", token.get("access_token").toString());
        map.put("activeTime", token.get("expires_in").toString());
        return map;
    }

    /**
     * @return
     */
    @Override
    public Map getQrCode() {
        ApplyWechatDTO applyWechatDTO = new ApplyWechatDTO();
        Map<String, String> stringMap = new HashMap<>(4);
        applyWechatDTO.setScene("a=1");
        applyWechatDTO.setWidth(150);
        BASE64Encoder encoder = new BASE64Encoder();
        Map token = this.getToken();
        byte[] scene = this.applyWechatFegin.getScene(applyWechatDTO, token);
        String encodeBuffer = encoder.encodeBuffer(this.applyWechatFegin.getScene(applyWechatDTO, token)).trim();
        stringMap.put("code", encodeBuffer);
        stringMap.put("activeTime", token.get("activeTime").toString());
        return stringMap;
    }


    /**
     * 获取预审批申请编号
     *
     * @param businessType
     * @param certNo
     * @return
     */
    @Override
    public String getPreApproveInfoApplyNO(String businessType, String certNo) {
        List<String> applyStatusList = new ArrayList<>();
        applyStatusList.add(ApplyConstants.PRE_APPROVE_PASS);
        applyStatusList.add(ApplyConstants.LEVEL_B);
        applyStatusList.add(ApplyConstants.LEVEL_C);
        applyStatusList.add(ApplyConstants.LEVEL_D);
        //获取状态为通过/abcd级的预审批信息
        PreApproveInfo preApproveInfo = this.baseMapper.selectOne(Wrappers.<PreApproveInfo>query().lambda()
                .eq(PreApproveInfo::getBusinessType, businessType)
                .eq(PreApproveInfo::getCertNo, certNo).in(PreApproveInfo::getApplyStatus, applyStatusList));
        if (preApproveInfo != null) {
            return preApproveInfo.getApplyNo();
        }
        return null;
    }

    /**
     * 通过申请编号、客户信息、证件号码查询预审批信息
     *
     * @param condition
     * @return
     */
    @Override
    public PreApproveInfo getPreApproveInfo(PreApproveCondition condition) {

        PreApproveInfo preApproveInfo = this.baseMapper.selectOne(Wrappers.<PreApproveInfo>query().lambda()
                .eq(PreApproveInfo::getBusinessType, condition.getBusinessType())
                .eq(PreApproveInfo::getCustName, condition.getCustName())
                .eq(PreApproveInfo::getCertNo, condition.getCertNo()));
        return preApproveInfo;
    }

    /**
     * 更新人脸识别、三要素、签约结果,订单状态
     *
     * @param condition
     */

    @Override
    public PreApproveInfo updatePreApproveInfo(PreApproveCondition condition) {

        PreApproveInfo preApproveInfo = this.getById(condition.getId());
        if (preApproveInfo != null) {
            if (StringUtil.isNotBlank(condition.getFaceResult())) {
                preApproveInfo.setFaceResult(condition.getFaceResult());
            }
            if (StringUtil.isNotBlank(condition.getSignResult())) {
                preApproveInfo.setSignResult(condition.getSignResult());
            }
            if (StringUtil.isNotBlank(condition.getThreeCaResult())) {
                preApproveInfo.setThreeCaResult(condition.getThreeCaResult());
            }
            //更新预审批单子状态未审核中
            preApproveInfo.setApplyStatus(ApplyConstants.PRE_PENDDING);
            this.baseMapper.updateById(preApproveInfo);
        }
        return preApproveInfo;
    }

    /**
     * @return
     */
    @Override
    public Map getSmallProgramQrCode(TencentCloudNuclearBodyCondition condition) {
        ApplyWechatDTO applyWechatDTO = new ApplyWechatDTO();
        Map<String, String> stringMap = new HashMap<>(4);
        String uuId = UUID.randomUUID().toString().replaceAll("-", "");
        applyWechatDTO.setScene(uuId);
        log.info("redis缓存key:" + uuId);
        applyWechatDTO.setWidth(150);
        BASE64Encoder encoder = new BASE64Encoder();
        Map token = this.getToken();
        JSONObject json = new JSONObject();
        //签约场景
        json.put("signScene", condition.getSignScene());
        //redis缓存key
        if (MESSAGE_TYPE_ZERO.equals(condition.getSignScene())) {
            //预审批表主键
            json.put("preId", condition.getPreId().toString());
        } else {
            //客户信息表主键、申请编号
            json.put("applyNo", condition.getApplyNo());
            json.put("custId", condition.getCustId().toString());
        }
        stringRedisTemplate.opsForValue().set(uuId, json.toJSONString(), 30, TimeUnit.MINUTES);
        String encodeBuffer = encoder.encodeBuffer(this.applyWechatFegin.getScene(applyWechatDTO, token)).trim();
        log.info("二维码-String:{}", encodeBuffer);
        stringMap.put("code", encodeBuffer);
        stringMap.put("uuId", uuId);
        stringMap.put("activeTime", token.get("activeTime").toString());
        return stringMap;
    }

    /**
     * 保存MD5到file
     */
    public List<ComAttachmentFile> saveOrUpdateFile(List<ContractFileVo> contractFileVos, String params) {

        List<ComAttachmentFile> outList = new ArrayList<ComAttachmentFile>();
        for (ContractFileVo contractFileVo : contractFileVos) {
            ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda().eq(ComAttachmentManagement::getUniqueCode, contractFileVo.getType()));
            if (ObjectUtil.isNotNull(comAttachmentManagement)) {
                ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
                comAttachmentFile.setBelongNo(params);
                comAttachmentFile.setBusiNo(params);
                comAttachmentFile.setAttachmentCode(String.valueOf(comAttachmentManagement.getId()));
                comAttachmentFile.setAttachmentName(comAttachmentManagement.getAttachmentName());
                comAttachmentFile.setFileStatus("standard");
                comAttachmentFile.setFileType(contractFileVo.getSuffix());
                comAttachmentFile.setFileId(contractFileVo.getMd5());
                comAttachmentFile.setHistoryVersion(contractFileVo.getVersion());
                comAttachmentFile.setIsElectronic(ApplyConstants.ZERO);
                comAttachmentFile.setFileName(contractFileVo.getFileName());
                comAttachmentFile.setUploadTime(new Date());
                comAttachmentFile.setCreateBy(SecurityUtils.getUsername());
                //存到file表
                this.comAttachmentFileService.save(comAttachmentFile);
                log.info("{}", comAttachmentManagement.getAttachmentName() + "更新成功");
                outList.add(comAttachmentFile);
            }
        }
        return outList;
    }

    /**
     * 保存预审批信息
     *
     * @param preApproveInfo
     */
    public void savePreInfo(PreApproveInfo preApproveInfo) {
        preApproveInfo.setId(null);
        //不是同一家
        preApproveInfo.setApplyStatus(ApplyConstants.PRE_APPROVE_PRE_SUBMIT);
        //新增时的创建人
        preApproveInfo.setCreateBy(SecurityUtils.getUsername());
        //新增时的申请时间
        preApproveInfo.setApplyDate(new Date());
        //部门id
        preApproveInfo.setDeptId(SecurityUtils.getUser().getDeptId().toString());
        //新增时的创建时间
        preApproveInfo.setCreateTime(new Date());
        preApproveInfo.setSellerRealName(SecurityUtils.getUser().getUserRealName());
        //渠道id
        preApproveInfo.setChannelId(SecurityUtils.getUser().getUserExtInfo().getLong("channelId"));
        preApproveInfo.setChannelName(SecurityUtils.getUser().getUserExtInfo().getJSONObject("channelInfo").get("channelFullName").toString());
        //保存并生成二维码
        String applyNo = applySequenceService.getApplyNo(preApproveInfo.getBusinessType());
        log.info("预审批临时编号变更正是编号:{}", applyNo);
        preApproveInfo.setApplyNo(applyNo);
        this.save(preApproveInfo);
    }

    /**
     * 预审批的单子复制到进件
     *
     * @param applyNo
     * @param condition
     */
    public void copyPreInfoToApply(String applyNo, ApplyReportCondition condition) {

        PreApproveInfo preApproveInfo = this.getById(condition.getPreId());
        if (preApproveInfo != null) {
            ApplyCustBaseInfo custInfo = new ApplyCustBaseInfo();
            custInfo.setApplyNo(applyNo);
            custInfo.setCustName(preApproveInfo.getCustName());
            custInfo.setCertType("00001");// 证件类型，默认身份证
            custInfo.setCertNo(preApproveInfo.getCertNo());
            custInfo.setCertEndDate(preApproveInfo.getCertEndDate());
            custInfo.setCustType(CustType.PERSON.getIndex());
            custInfo.setCustRole(ApplyConstants.PRINCIPAL_BORROWER);
            custInfo.setTelPhone(preApproveInfo.getTelPhone());
            custInfo.setSignResult(preApproveInfo.getSignResult());
            custBaseInfoMapper.insert(custInfo);
            // 身份正反面
            List<ComAttachmentFile> mainFrontList = this.applyOrderInfoMapper.getIdCardImage(String.valueOf(condition.getPreId()), "preBorrowerIdcardFront", "preApply");
            if (CollectionUtil.isNotEmpty(mainFrontList)) {
                ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
                BeanUtil.copyProperties(mainFrontList.get(0), comAttachmentFile);
                comAttachmentFile.setId(null);
                comAttachmentFile.setBusiNo(applyNo);
                comAttachmentFile.setBelongNo(applyNo);
                comAttachmentFile.setCreateTime(new Date());
                ComAttachmentManagement attachmentManagement = attachmentManagementService.getAttachmentManagement("orderApply", "mainBorrowerIdcardFront");
                if (attachmentManagement != null) {
                    comAttachmentFile.setAttachmentCode(String.valueOf(attachmentManagement.getId()));
                    comAttachmentFile.setAttachmentName(attachmentManagement.getAttachmentName());
                }
                comAttachmentFile.setFileStatus(StatusEnum.DRAFT.getValue());
                comAttachmentFile.setIsElectronic(WhetherEnum.YES.getIndex());
                comAttachmentFile.setFileSource("com_attachment_management");
                comAttachmentFileService.save(comAttachmentFile);
            }
            List<ComAttachmentFile> mainBackList = this.applyOrderInfoMapper.getIdCardImage(String.valueOf(condition.getPreId()), "preBorrowerIdcardBack", "preApply");
            if (CollectionUtil.isNotEmpty(mainBackList)) {
                ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
                BeanUtil.copyProperties(mainBackList.get(0), comAttachmentFile);
                comAttachmentFile.setId(null);
                comAttachmentFile.setBusiNo(applyNo);
                comAttachmentFile.setBelongNo(applyNo);
                comAttachmentFile.setCreateTime(new Date());
                ComAttachmentManagement attachmentManagement = attachmentManagementService.getAttachmentManagement("orderApply", "mainBorrowerIdcardBack");
                if (attachmentManagement != null) {
                    comAttachmentFile.setAttachmentCode(String.valueOf(attachmentManagement.getId()));
                    comAttachmentFile.setAttachmentName(attachmentManagement.getAttachmentName());
                }
                comAttachmentFile.setFileStatus(StatusEnum.DRAFT.getValue());
                comAttachmentFile.setIsElectronic(WhetherEnum.YES.getIndex());
                comAttachmentFile.setFileSource("com_attachment_management");
                comAttachmentFileService.save(comAttachmentFile);
            }
            // 征信授权书
            List<ComAttachmentFile> creditList = this.applyOrderInfoMapper.getIdCardImage(String.valueOf(condition.getPreId()), "creditAuthorizationFile", "orderApply");
            if (CollectionUtil.isNotEmpty(creditList)) {
                ComAttachmentFile comAttachmentFile = new ComAttachmentFile();
                BeanUtil.copyProperties(creditList.get(0), comAttachmentFile);
                comAttachmentFile.setId(null);
                comAttachmentFile.setBusiNo(applyNo);
                comAttachmentFile.setBelongNo(applyNo);
                comAttachmentFile.setCreateTime(new Date());
                comAttachmentFile.setFileSource("com_attachment_management");
                comAttachmentFile.setFileStatus(StatusEnum.DRAFT.getValue());
                comAttachmentFile.setIsElectronic(WhetherEnum.YES.getIndex());
                comAttachmentFileService.save(comAttachmentFile);
            }
        }
    }
}
